import React, { Component } from 'react'

import styles from './index.module.css'

const MyContext = React.createContext()

export default class A extends Component {
  state = {
    name: 'Judith',
    age: 19,
  }

  render() {
    const { name, age } = this.state;

    return (
      <div className={styles.parent}>
        我是A组件，名称是: {name}, 年龄是: {age}
        <MyContext.Provider value={{ name, age }}>
          <B />
        </MyContext.Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className={styles.child}>
        我是B组件
        <C />
        <D />
        <E />
      </div>
    )
  }
}

class C extends Component {
  static contextType = MyContext

  render() {
    const { name, age } = this.context
    return (
      <div className={styles.grand}>
        我是C组件，名称是: {name}, 年龄是: {age}
      </div>
    )
  }
}

function D() {
  return (
    <div className={styles.grand}>
      <MyContext.Consumer>
        {
          data => {
            return (
              <div>
                我是D组件，名称是: {data.name}, 年龄是: {data.age}
              </div>
            )
          }
        }
      </MyContext.Consumer>
    </div>
  );
}

function E() {
  const data = React.useContext(MyContext);

  return (
    <div className={styles.grand}>
      <div>
        我是E组件，名称是: {data.name}, 年龄是: {data.age}
      </div>
    </div>
  );
}

